import { camelCase } from "lodash";

function isPathEndOfName(path, name) {
  return new RegExp(`${name}$`).test(path);
}

function isPathContainNames(path, names) {
  return names.some((name) => isPathEndOfName(path, name));
}

/*
 * req参数只能像这样传： require.context(path,deep,regExp)
 * req: require.context("@/store", false, /\.js$/),
 * exclude: 该目录下需要排除的，v 是由文件相对path的路径加文件名称的字符串
 * exclude: (v) => v.indexOf("index") >= 0
 * */
export default function importFolder(req, exclude) {
  try {
    exclude = typeof exclude === "function" ? exclude : () => {};
    return req.keys().reduce((res, key) => {
      const file = req(key);
      const module = file.default || file;
      const name = module.name || camelCase(key.replace(/(.js$)|[./]/g, ""));
      return Object.assign(
        res,
        exclude(key, { isPathContainNames }) ? {} : { [name]: module }
      );
    }, {});
  } catch (error) {
    console.error(error);
    return {};
  }
}
